package com.demo.jianjunhuang.webviewdemo;

import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author jianjunhuang.me@foxmail.com
 *         create on 2017/7/14.
 */

public class DownLoadHTML extends AsyncTask<Void, Void, String> {

    public static interface HTMLPageDownloaderListener {
        public abstract void completionCallBack(String html);
    }

    public HTMLPageDownloaderListener listener;
    public String link;

    public DownLoadHTML(String aLink, HTMLPageDownloaderListener aListener) {
        listener = aListener;
        link = aLink;
    }

    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub
        StringBuffer stringBuffer = new StringBuffer();
        String html = "";
        try {
            URL url = new URL(link);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                html = stringBuffer.toString();
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return html;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (!isCancelled()) {
            listener.completionCallBack(result);
        }
    }
}
